package com.qianxx.network.converter;

import com.alibaba.fastjson.JSON;
import com.qianxx.network.RequestBean;
import com.qianxx.network.RequestError;
import com.qianxx.utils.RsaUtil;

import java.io.IOException;
import java.lang.reflect.Type;

import okhttp3.ResponseBody;
import retrofit2.Converter;


public class FastJsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {

    private final Type type;

    FastJsonResponseBodyConverter(Type type) {
        this.type = type;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {
        String s = value.string();
        // 获取 Api 实体
//        if (type == ApiEntity.class) {
//            return JSON.parseObject(s, type);
//        }
        // 获取封装实体
        RequestBean bean;
        try {
            bean = JSON.parseObject(s, RequestBean.class);
        } catch (Exception e) {
            bean = null;
            s = s.replace("\"", "");
        }
        if (bean == null) {
            String jsonData = null;
            if ("error".equals(s)) {
                return null;
            }
            try {
                jsonData = RsaUtil.decryptByPrivate(RsaUtil.decodeURL(s), RsaUtil.PRIVATE_KEY_DEFAULT);
            } catch (Exception e1) {
                e1.printStackTrace();
            }
            if (jsonData == null) {
                return null;
            }
            bean = JSON.parseObject(jsonData, RequestBean.class);
        }
        // 通过解析出来的实体判断
        if (null != bean && bean.getSuccess()) {
            if (type == String.class)
                return (T) bean.getData();
            return JSON.parseObject(bean.getData(), type);
        }
        throw new RequestError(bean);
    }
}
